package com.newway.back.security;

import com.newway.LoginUser;
import com.newway.back.util.SecurityUserContext;
import com.newway.util.JwtTokenUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TokenFilter extends OncePerRequestFilter {

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Resource
    //@Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver handlerExceptionResolver;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String requestURI = request.getRequestURI();
        if("/back/login".equals(requestURI)||request.getRequestURI().startsWith("/front/")||requestURI.startsWith("/wechat/")){
            chain.doFilter(request, response);
            return;
        }
        LoginUser loginUser = jwtTokenUtil.getLoginUser(request);
        if(loginUser!=null ){
            MyUserDetails myUserDetails = loginUser.getMyUserDetails();
            UsernamePasswordAuthenticationToken auth =
                    new UsernamePasswordAuthenticationToken(myUserDetails, null, myUserDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(auth);
            chain.doFilter(request, response);
        }else{
            handlerExceptionResolver.resolveException(request,response,null,new BadCredentialsException("无效凭证"));
        }
        return;
    }
}
